package com.andy.common.extend

import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import com.google.android.material.color.MaterialColors
import java.util.Locale
import java.util.regex.Pattern


fun TextView.setFontFamily(fontId: Int) {
    typeface = ResourcesCompat.getFont(context, fontId)
}

fun TextView.showHighText(
    contentText: String,
    vararg keyword: String,
    color: Int = MaterialColors.getColor(this, android.R.attr.colorPrimary)
) {
    if (contentText.isEmpty() || keyword.isEmpty()) {
        this.text = ""
        return
    }
    val stringBuilder = SpannableStringBuilder(contentText)
    val lowercaseKeywords = keyword.map { it.lowercase(Locale.getDefault()) }
    val regex = lowercaseKeywords.joinToString("|")
    val matcher = Pattern.compile(regex).matcher(contentText.lowercase(Locale.getDefault()))
    while (matcher.find()) {
        val start = matcher.start()
        val end = matcher.end()
        stringBuilder.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
    }
    this.text = stringBuilder
}
